from flask import request, jsonify, make_response
from flask_jwt_extended import create_access_token

from .extensions import db
from .models import User
from werkzeug.security import generate_password_hash, check_password_hash


def init_auth_routes(app):
    @app.route('/api/auth/login', methods=['POST', 'OPTIONS'])
    def login():
        if request.method == 'OPTIONS':
            response = make_response()
            response.headers.add('Access-Control-Allow-Origin', 'http://localhost:5173')
            response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
            response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
            response.headers.add('Access-Control-Allow-Credentials', 'true')
            return response
        data = request.get_json()
        user = User.query.filter_by(username=data.get('username')).first()

        if user and user.check_password(data.get('password')):
            # 生成token
            token = create_access_token(identity=str(user.user_id))
            return jsonify({
                'success': True,
                'message': '登录成功',
                'token': token,
                'username': user.username
            })
        return jsonify({
            'success': False,
            'message': '用户名或密码错误'
        })

    @app.route('/api/auth/register', methods=['POST', 'OPTIONS'])
    def register():
        if request.method == 'OPTIONS':
            return jsonify({}), 200
        data = request.get_json()
        if User.query.filter_by(username=data.get('username')).first():
            return jsonify({
                'success': False,
                'message': '用户名已存在'
            })

        new_user = User(
            username=data.get('username'),
            password=generate_password_hash(data.get('password'))
        )

        try:
            db.session.add(new_user)
            db.session.commit()
            return jsonify({
                'success': True,
                'message': '注册成功'
            })
        except Exception as e:
            db.session.rollback()
            return jsonify({
                'success': False,
                'message': f'注册失败: {str(e)}'
            })